#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: permission.py
@time: 2023/10/28 16:46
@desc: 
"""
import json
import os
from datetime import datetime

from tornado import gen

from backend.conf import config
from backend.conf.config import snowflake
from backend.tvadmin.system.models.factory import Factory
from backend.tvadmin.system.models.permission import Dept, Role, Post, File, ConfigSettings
from backend.tvadmin.utils.base_requeset import BaseHttpHandler, BaseAuthCheckHttpHandler
from backend.tvadmin.utils.base_response import SuccessResponse, ErrorResponse
from backend.tvadmin.utils.page_utils import pagination, self_pagination


class DeptHandler(BaseHttpHandler):

    @gen.coroutine
    def get(self):
        # result = self.db.query(Dept).filter(Dept.is_delete == 0).all()
        # result = list(
        #     self.db.query(Dept).order_by(Dept.create_datetime.desc()).filter(Dept.is_delete == 0).
        #     with_entities(Dept.id, Dept.name, Dept.sort).all())
        # result = self.db.query(Dept).order_by(Dept.create_datetime.desc()).filter(Dept.is_delete == 0).all()
        # result = Dept.query(filter=(Dept.id == 1)).all()
        # result = Dept.query((Dept.id==1))
        # result = Dept.query("id = 1 and name = '上海巨人网络科技有限公司'", Dept)
        id = self.request.body_arguments.get("id")
        # result = Dept.query(f"id = {id} and name ='{}'", Dept)
        result = Dept.query("id = 1 and name = '上海巨人网络科技有限公司'", Dept)
        # result = [{"id": i.id, "name": i.name, "sort": i.sort} for i in result]
        data = pagination(result)
        return self.write(SuccessResponse(data=data))

    def post(self):
        request_data = self.request.data
        dept_obj = Dept(**request_data)
        Dept.add(dept_obj, self.request)
        return self.write(SuccessResponse())

    def getApiById(self, *args, **kwargs):
        data = json.loads(self.body)
        id = data.get("id")
        # id = self.request.data.get("id")
        # data = Dept.query_first(f"id = {id}", Dept)
        data = Dept.first(id=id)
        # result = Dept.query("id = 1 and name = '上海巨人网络科技有限公司'", Dept)
        # result = [{"id": i.id, "name": i.name, "sort": i.sort} for i in result]
        # data = pagination(result)
        return self.write(SuccessResponse(data=data))


class SingleDeptHandler(BaseHttpHandler):

    @gen.coroutine
    def get(self, *args, **kwargs):
        result = self.db.query(Dept).filter(Dept.is_delete == 0).all()
        data = pagination(result)
        return self.write(SuccessResponse())

    def post(self, *args, **kwargs):
        # self.db.
        pass

    def delete(self, *args, **kwargs):
        pass

    def put(self, *args, **kwargs):
        id = self.request.arguments.get("id")
        result = self.db.query(Dept).filter(Dept.is_delete == 0, ).all()
        data = pagination(result)


class RoleHandler(BaseAuthCheckHttpHandler):

    @gen.coroutine
    def get(self, *args, **kwargs):
        # result = self.db.query(Role).filter(Role.is_delete == 0).all()
        result = Role.query("is_delete = 0", Role)
        data = pagination(result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        role_obj = Role(
            name="超级管理员",
            role_key="admin",
            status=1,
            is_admin=1,
        )
        Role.add(role_obj)
        return self.write(SuccessResponse())

    def delete(self, *args, **kwargs):
        # 第一
        # id = self.request.arguments.get("id")
        # result = self.db.query(Role).filter(Role.id == 1).all()
        # self.db.query(Role).filter(Role.id == 1).update({Role.is_delete: 1})
        # self.db.commit()
        # print(result)
        #
        # result = Dept.all()
        # for i in result:
        #     print(i.id)
        #     print(i.is_delete)
        # print(result)
        id = self.request.data.get("id")
        result = Role.filter(id=id, name="超级管理员")
        print(result)
        return self.write(SuccessResponse(data=[]))

    def put(self, *args, **kwargs):
        # id = self.request.arguments.get("id")
        # result = self.db.query(Dept).filter(Dept.is_delete == 0, ).all()
        # data = pagination(result)
        # role_obj = Role.filter(id=1)

        # 更新
        # id = self.request.data.get("id")
        # self.db.query(Role).filter_by(id=id).update({**self.request.data})

        # 更新
        id = self.request.data.get("id")
        result = Role.filter(id=id, name="超级管理员")
        request_data = self.request.data
        del request_data["id"]
        Role.filter_update(filter_args={"id": id}, update_args=request_data)


# class FactoryModelViewSet(BaseAuthCheckHttpHandler):
#     def get(self, *args, **kwargs):
#         result = Factory.all_list()
#         # data = pagination(result,page= self.request.data.get("pagenum"),page_size=self.request.data.get("pagesize"))
#         data = self_pagination(self.request, data_list=result)
#         return self.write(SuccessResponse(data))
#
#     def post(self, *args, **kwargs):
#         factory_name = self.request.data.get("factory_name")
#         license_id = self.request.data.get("license_id")
#         factory_id = self.request.data.get("factory_id")
#         phone = self.request.data.get("phone")
#         factory_ = Factory()
#         factory_.factory_name = factory_name
#         factory_.phone = phone
#         factory_.factory_id = factory_id
#         factory_.license_id = license_id
#         data = Factory.add(factory_)
#
#         return self.write(SuccessResponse(data))
#
#     def delete(self, *args, **kwargs):
#         # 第一
#         # id = self.request.arguments.get("id")
#         # result = self.db.query(Role).filter(Role.id == 1).all()
#         # self.db.query(Role).filter(Role.id == 1).update({Role.is_delete: 1})
#         # self.db.commit()
#         # print(result)
#         #
#         # result = Dept.all()
#         # for i in result:
#         #     print(i.id)
#         #     print(i.is_delete)
#         # print(result)
#         # id = self.request.data.get("id")
#         # result = Role.filter(id=id, name="超级管理员")
#         # print(result)
#
#         id = self.request.data.get("id")
#         # factory = FactoryModel.filter(id=id)
#         factory = Factory.first(id=id)
#         # factory = FactoryModel.get_column_names()
#         # factory = FactoryModel.__repr__()
#         # factory = FactoryModel.__tablename__
#         if factory:
#             print(factory)
#             Factory.delete_soft(id=id)
#         return self.write(SuccessResponse(data=[]))
#
#     def put(self, *args, **kwargs):
#         # id = self.request.arguments.get("id")
#         # result = self.db.query(Dept).filter(Dept.is_delete == 0, ).all()
#         # data = pagination(result)
#         # role_obj = Role.filter(id=1)
#
#         # 更新
#         # id = self.request.data.get("id")
#         # self.db.query(Role).filter_by(id=id).update({**self.request.data})
#
#         # # 更新
#         # id = self.request.data.get("id")
#         # result = Role.filter(id=id, name="超级管理员")
#         # request_data = self.request.data
#         # del request_data["id"]
#         # Role.filter_update(filter_args={"id": id}, update_args=request_data)
#         id = self.request.data.get("id")
#         if id:
#             factory = Factory.first(id=id)
#             if factory:
#                 Factory.filter_update(filter_args={"id": id}, update_args=self.request.data)
#                 factory = Factory.query_first(id=id)
#
#             return self.write(SuccessResponse(data=factory))


class PostModelViewSet(BaseAuthCheckHttpHandler):
    """
    Demo example
    """

    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = Post.filter_list(self.request.data)
        else:
            result = Post.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        post = Post()
        post.name = self.request.data.get("name")
        post.post_key = self.request.data.get("post_key")
        post.sort = self.request.data.get("sort")
        post.remark = self.request.data.get("remark")
        data = Post.add(post, self.request)
        return self.write(SuccessResponse(data))

    def put(self, *args, **kwargs):
        id = self.request.data.get("id")
        if id:
            post = Post.first(id=id)
            if post:
                Post.filter_update(filter_args={"id": id}, update_args=self.request.data, request=self.request)
                post = Post.query_first_dict(id=id)
                return self.write(SuccessResponse(data=post))
            else:
                return self.write(ErrorResponse(msg="岗位不存在"))

    def delete(self, *args, **kwargs):
        id = self.request.data.get("id")
        post = Post.first(id=id)
        if post:
            Post.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="岗位不存在"))


class FactoryModelViewSet(BaseAuthCheckHttpHandler):
    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = Factory.filter_list(self.request.data)
        else:
            result = Factory.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        factory_name = self.request.data.get("factory_name")
        license_id = self.request.data.get("license_id")
        factory_id = self.request.data.get("factory_id")
        phone = self.request.data.get("phone")
        factory_ = Factory()
        factory_.factory_name = factory_name
        factory_.phone = phone
        factory_.factory_id = factory_id
        factory_.license_id = license_id
        data = Factory.add(factory_, self.request)
        return self.write(SuccessResponse(data))

    def put(self, *args, **kwargs):
        id = self.request.data.get("id")
        if id:
            factory = Factory.first(id=id)
            if factory:
                Factory.filter_update(filter_args={"id": id}, update_args=self.request.data, request=self.request)
                factory = Factory.query_first_dict(id=id)
                return self.write(SuccessResponse(data=factory))
            else:
                return self.write(ErrorResponse(msg="岗位不存在"))

    def delete(self, *args, **kwargs):
        id = self.request.data.get("id")
        factory = Factory.first(id=id)
        if factory:
            Factory.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="工厂不存在"))


class FileModelViewSet(BaseAuthCheckHttpHandler):
    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = Factory.filter_list(self.request.data)
        else:
            result = Factory.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        media_path = config.settings.get("media_path")
        today = f"{datetime.now().year}-{datetime.now().month}-{datetime.now().day}"
        file_path = os.path.join(media_path, today)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        file_metas = self.request.files[
            'file']  # 提取表单中‘name’为‘file’的文件元数据(一个文件元包括:[{'body':' XXX', 'content_type':'XXXX', 'filename':'XXXX'}])
        for meta in file_metas:
            filename = str(meta['filename'])
            tag = filename.split(".")[-1].lower()
            key = str(snowflake.get_id()) + "." + tag
            filepath = os.path.join(file_path, key)
            with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改(注意学习with ... as 关键词的用法)
                up.write(meta['body'])
            file_obj = File()
            file_obj.name = filename
            file_obj.tag = tag
            file_obj.url = file_path
            file_obj.key = key
            file = File.add(file_obj, self.request)
            return self.write(SuccessResponse(file))

    def put(self, *args, **kwargs):
        id = self.request.data.get("id")
        if id:
            factory = Factory.first(id=id)
            if factory:
                Factory.filter_update(filter_args={"id": id}, update_args=self.request.data, request=self.request)
                factory = Factory.query_first_dict(id=id)
                return self.write(SuccessResponse(data=factory))
            else:
                return self.write(ErrorResponse(msg="岗位不存在"))

    def delete(self, *args, **kwargs):
        id = self.request.data.get("id")
        factory = Factory.first(id=id)
        if factory:
            Factory.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="工厂不存在"))


class ConfigSettingsModelViewSet(BaseAuthCheckHttpHandler):
    """
   参数获取管理
    """

    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = ConfigSettings.filter_list(self.request.data)
        else:
            result = ConfigSettings.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))


class GetCondfigModelViewSet(BaseAuthCheckHttpHandler):
    """
   参数获取管理
    """

    def get(self, *args, **kwargs):
        config_key_dict = self.redis.get("config_key_dict")
        if not config_key_dict:
            result = ConfigSettings.all_list()
            config_key_dict = {ele.get('key'): ele.get('value') for ele in
                               result}
            config_key_dict = json.dumps(config_key_dict)
            self.redis.set("config_key_dict", config_key_dict, 86400)
        if config_key_dict != "null":
            config_key_dict = json.loads(config_key_dict)
            return self.write(SuccessResponse(config_key_dict))
        else:
            return self.write(SuccessResponse())

    def delete(self, *args, **kwargs):
        config_key_dict = self.redis.delete("config_key_dict")
        return self.write(SuccessResponse())
